import {
  getUserInfo as _getUserInfo,
  wxLogin as _wxLogin,
  getWxCode,
  Login as _Login,
} from '@/api/login/index'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { IUserInfoVo } from '@/api/login/login.typings'

// 初始化状态
const userInfoState: IUserInfoVo = {
  userId: 0,
  name: '',
  avatar: '/static/images/default-avatar.png',
  phone: '',
  companyName: '',
  position:'',
  gender:''
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 定义用户信息
    const userInfo = ref<IUserInfoVo>({ ...userInfoState })
    // 设置用户信息
    const setUserInfo = (val: IUserInfoVo) => {
      // 若头像为空 则使用默认头像
      if (!val.avatar) {
        val.avatar = userInfoState.avatar
      }
      userInfo.value = val
    }
    const setUserAvatar = (avatar: string) => {
      userInfo.value.avatar = avatar
    }
    // 删除用户信息
    const removeUserInfo = () => {
      userInfo.value = { ...userInfoState }
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('access_token')
    }
    /**
     * 获取用户信息
     */
    const getUserInfo = async (id: number) => {
      const res = await _getUserInfo({ userId: id })
      const obj = res.data

      setUserInfo(obj)
      uni.setStorageSync('userInfo', obj)

      // TODO 这里可以增加获取用户路由的方法 根据用户的角色动态生成路由
      return res
    }
    /**
     * 退出登录 并 删除用户信息
     */
    const logout = async () => {
      // _logout()
      removeUserInfo()
    }
    /**
     * 微信登录
     */
    const wxLogin = async (other) => {
      // 获取微信小程序登录的code
      const data = await getWxCode()
      const obj = {
        code: data.code,
        iv: other.iv,
        encryptedData: other.encryptedData,
        wxCode: other.wxCode,
      }
      console.log('微信登录code', obj)

      const res = await _wxLogin(obj)
      uni.setStorageSync('access_token', res.data.token||res.data.access_token)
      uni.setStorageSync('phone', res.data.phone)

      let userObj = {
        userId: res.data.userId,
        name: res.data.name,
        avatar: res.data.avatar,
        phone: res.data.phone,
        companyName: res.data.companyName,
      }
      setUserInfo(userObj)

      // await getUserInfo(res.data.userId)
      return res
    }
    /**
     * 普通登录
     */
    const Login = async (data) => {
      const obj = {
        phone: data.phone,
      }
      const res = await _Login(obj)
      // const res = {
      //   data: {
      //     avatar: 'https://oss.laf.run/ukw0y1-site/avatar.jpg',
      //     id: 100,
      //     username: 'admin',
      //     phone: '17377772214',
      //   },
      // }
      uni.setStorageSync('access_token', res.data.token)
      getUserInfo(res.data.userId)
      return res
    }

    return {
      userInfo,
      wxLogin,
      getUserInfo,
      setUserInfo,
      setUserAvatar,
      logout,
      Login,
      removeUserInfo,
    }
  },
  {
    persist: true,
  },
)
